<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

/**
 * Ajax action to publish a temporary document or set a revision into temporary document (table f_temp)
 * Called by publishPage() from jQueryBackend.js
 */
class m_backoffice_actions_AjaxPublishTempDocumentAction extends m_backoffice_extends_Action
{
	public function execute()
	{
		// Retrieve parameters
		$documentId = $this->getRequestParameter("documentId");
		$documentLang = $this->getRequestParameter("documentLang");
		$revision = $this->getRequestParameter("revision");
		$withRevision = $this->getRequestParameter("withRevision");
		
		$withRevision == "true" ? $withRevision = true : $withRevision = false;
		
		// Initialize the temporary document service
		$tempDocService = m_backoffice_services_TempDocService::getInstance();

		if(intval($documentId) > 0)
		{
			// If document is a revision
			if($revision > 0)
			{
				// Load the revision and set the author
				$document = f_document_Provider::getInstance()->getByUniqueId($documentId, $documentLang)->getRevision(intval($revision));
				$document->setAuthor($this->getUser()->getLogin());
				
				$this->restoreBlocks($document);
				
				// Delete old temporary document and save revision into a new one
				$tempDocService->deleteTempDocument($documentId, $documentLang);
				$tempDocService->saveTemporaryDocument($document);
			}
			else
			{
				// Get the temporary document set the author and save
				$document = $tempDocService->getTemporaryDocument($documentId, $documentLang);
				$document->setAuthor($this->getUser());
				$this->fireInfo($document);
				if($document->getModel() == "modules_website/page")
				{
					$document = $this->manageBlocks($document, $withRevision);
					
					if($document->getSwitchPage())
					{
						$this->switchPage($document);
						$document->setPublicationstatus("PUBLISHED");
					}					
				}

				$tempDocService->deleteTempDocument($documentId, $documentLang);
				$document->save($withRevision);
			}
		}
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight("website_ValidatePage");
	}

    public function errorHandler()
    {
        return null;
    }
	
	/**
	 * Remove blocks with deleted status
	 * @return m_website_documents_Page
	 * @param m_website_documents_Page $page
	 */
	private function manageBlocks($page, $withRevision)
	{
		$blocks = $page->getAllBlocks();
		$documentProvider = f_document_Provider::getInstance();
		$tempDocService = m_backoffice_services_TempDocService::getInstance();
		
		foreach($blocks as $key => $block)
		{
			if(isset($block["blockStatus"]) && $block["blockStatus"] == "DELETED")
			{				
				switch ($block["action"]) {
					case "front_FreeContent":
						if($block["contentId"] > 0 && $block["blockLang"] != "")
						{							
							$documentProvider	->getByUniqueId($block["contentId"], $block["blockLang"])
												->setPublicationstatus("DELETED")->save(false);
						}
					break;
				}
				
				$page->deleteBlockById($key);				
			}
			else
			{
                if(isset($block['withValidation']) && $block['withValidation'] == 'true')
                {
                    if(isset($block["contentId"]) && $block["contentId"] != null && $block["contentId"] != '')
                    {
                        if($tempDocService->hasTemporary($block["contentId"], $block["blockLang"]))
                        {
                            $doc = $tempDocService->getTemporaryDocument($block["contentId"], $block["blockLang"]);
                            $tempDocService->deleteTempDocument($block["contentId"], $block["blockLang"]);
                        }
                        else
                        {
                            $doc = $documentProvider->getByUniqueId($block["contentId"], $block["blockLang"]);
                        }

                        $doc->setPublicationstatus("PUBLISHED");

                        if(method_exists($doc, 'setWebsiteId'))
                        {
                            $doc->setWebsiteId($page->getWebsiteId());
                        }

                        if(method_exists($doc, 'setPageId'))
                        {
                            $doc->setPageId($page->getUniqueId());
                        }
                            
                        $doc->setAuthor($this->getUser()->getLogin())->save($withRevision);

                        $block["revision"] = $doc->getLastRevisionNumber();

                        $page->setBlockParamsById($block["blockId"], $block);
                    }
				}
			}
		}
		
		return $page;
	}
	
	private function restoreBlocks($page)
	{
		$blocks = $page->getAllBlocks();
		$documentProvider = f_document_Provider::getInstance();
		$tempDocService = m_backoffice_services_TempDocService::getInstance();
		
		foreach($blocks as $key => $block)
		{
			switch ($block["action"]) {
				case "front_FreeContent":
					// If block has a linked document check if he has the PUBLISHED status
					if(isset($block["contentId"]) && $block["contentId"] != null)
					{
						$doc = $documentProvider->getByUniqueId($block["contentId"], $block["blockLang"])->getRevision($block["revision"]);
						$tempDocService->saveTemporaryDocument($doc);
					}
				break;
			}
		}
	}
	
	/**
	 * When another page have the same url swith other one to draft
	 * @return null
	 * @param m_website_documents_Page $page
	 */
	private function switchPage($page)
	{		
		$documentProvider = f_document_Provider::getInstance();
		
		$oldPage = $documentProvider->loadDocuments("modules_website/Page")
								->whereIsEqual("websiteId", $page->getWebsiteId())
								->whereIsEqual("document_publicationstatus", "PUBLISHED")
								->whereIsEqual("url", $page->getUrl())
								->whereIsNotEqual("document_uid", $page->getUniqueId())
								->retrieveFirstDocument($page->getLang());								
										
		if(!is_null($oldPage))
		{
			$menu = $oldPage->getIndexMenu();

			if(!is_null($menu))
			{
				$menu->setMenuPageId($page->getUniqueId())->save(false);
			}	
			
			$oldPage->setAuthor($this->getUser()->getLogin())->setPublicationstatus("DRAFT")->save(false);
		}
	}
}